<template>
  <div class="members-page">
    <Header />
    <main class="page-content">
      <div class="container">
        <h1 class="page-title">Members</h1>

        <div v-if="loading" class="loading"></div>
        <div v-else-if="error" class="error">{{ error }}</div>
        <template v-else>
          <!-- Principal Investigator (sequence_id=1) -->
          <section v-if="principalInvestigator.length > 0" class="section">
            <h2 class="section-title">Principal Investigator</h2>
            <div v-for="member in principalInvestigator" :key="member.user_id" class="pi-profile">
              <div class="pi-image">
                <img :src="getAvatarUrl(member.avatar)" :alt="member.name">
              </div>
              <div class="pi-info">
                <h3>{{ member.name }}</h3>
                <div class="contact-info">
                  <p v-if="member.phd"><strong>Ph.D. :</strong> {{ member.phd }}</p>
                  <p v-if="member.msc"><strong>M.Sc. :</strong> {{ member.msc }}</p>
                  <p v-if="member.me"><strong>M.E. :</strong> {{ member.me }}</p>
                  <p v-if="member.be"><strong>B.E. :</strong> {{ member.be }}</p>
                  <p v-if="member.email"><strong>📧 Email:</strong> <a :href="`mailto:${member.email}`">{{ member.email }}</a></p>
                  <p v-if="member.phone"><strong>📞 电话:</strong> {{ member.phone }}</p>
                  <p v-if="member.address"><strong>🏢 办公室:</strong> {{ member.address }}</p>
                  <p v-if="member.research_interests"><strong>🔬 Research Interests:</strong> {{ member.research_interests }}</p>
                </div>
                <div v-if="member.profile" class="bio" v-html="cleanProfile(member.profile)"></div>
                <div class="links">
                  <a v-if="member.homepage" :href="member.homepage" target="_blank" rel="noopener noreferrer" class="btn">个人主页</a>
                </div>
              </div>
            </div>
          </section>

          <!-- 其他分组，按 sequence_name 显示 -->
          <template v-for="group in otherGroups" :key="group.sequence_id">
            <section v-if="group && group.user_list && group.user_list.length > 0" class="section">
              <h2 class="section-title">{{ group.sequence_name }}</h2>
              <div :class="getGridClass(group.sequence_id)">
                <div v-for="member in group.user_list" :key="member.user_id" class="member-card">
                <div class="member-image">
                  <img :src="getAvatarUrl(member.avatar)" :alt="member.name">
                </div>
                <div class="member-info">
                  <h3>{{ member.name }}</h3>
                  <p v-if="member.phd" class="member-detail" v-html="`<strong>Ph.D.:</strong> ${cleanHtml(member.phd)}`"></p>
                  <p v-if="member.msc" class="member-detail" v-html="`<strong>M.Sc.:</strong> ${cleanHtml(member.msc)}`"></p>
                  <p v-if="member.me" class="member-detail" v-html="`<strong>M.E.:</strong> ${cleanHtml(member.me)}`"></p>
                  <p v-if="member.be" class="member-detail" v-html="`<strong>B.E.:</strong> ${cleanHtml(member.be)}`"></p>
                  <p v-if="member.research_interests" class="member-detail">
                    <strong>Research Interests:</strong><br>
                    {{ member.research_interests }}
                  </p>
                  <p v-if="member.email" class="member-detail"><strong>Email:</strong> <a :href="`mailto:${member.email}`">{{ member.email }}</a></p>
                </div>
              </div>
            </div>
            </section>
          </template>

          <!-- Post Members (sequence_id=22) -->
          <section v-if="postMembers.length > 0" class="section">
            <h2 class="section-title">{{ postMembersGroupName }}</h2>
            <div class="post-members-grid">
              <div v-for="member in postMembers" :key="member.user_id" class="post-member-card">
                <h3>{{ member.name }}</h3>
                <p v-if="member.position_name" class="post-member-detail">{{ member.position_name }}</p>
                <p v-if="member.graduation_destination" class="post-member-detail"><strong>Graduation destination:</strong><br/> {{ member.graduation_destination }}</p>
              </div>
            </div>
          </section>
          
        </template>
      </div>
    </main>
    <Footer />
  </div>
</template>

<script>
import Header from '../components/Header.vue'
import Footer from '../components/Footer.vue'
import { getMembersList, API_BASE_URL } from '@/utils/api'

export default {
  name: 'Members',
  components: {
    Header,
    Footer
  },
  data() {
    return {
      membersData: [],
      loading: false,
      error: null
    }
  },
  computed: {
    principalInvestigator() {
      const piGroup = this.membersData.find(item => item.sequence_id === 1)
      return piGroup ? piGroup.user_list : []
    },
    postMembers() {
      const postGroup = this.membersData.find(item => item.sequence_id === 22)
      return postGroup ? postGroup.user_list : []
    },
    postMembersGroupName() {
      const postGroup = this.membersData.find(item => item.sequence_id === 22)
      return postGroup ? postGroup.sequence_name : 'Post Members'
    },
    otherGroups() {
      // 排除 Principal Investigator (sequence_id === 1) 和 Post Members (sequence_id === 22)
      // 过滤掉没有 user_list 或 user_list 为空的分组
      return this.membersData.filter(item => 
        item && 
        item.sequence_id !== 1 && 
        item.sequence_id !== 22 && 
        item.user_list && 
        Array.isArray(item.user_list) && 
        item.user_list.length > 0
      )
    }
  },
  async mounted() {
    await this.fetchMembersList()
  },
  methods: {
    /**
     * 获取Members列表
     */
    async fetchMembersList() {
      this.loading = true
      this.error = null
      try {
        const data = await getMembersList()
        this.membersData = Array.isArray(data) ? data : []
      } catch (error) {
        console.error('获取Members列表失败:', error)
        this.error = error.message || '获取成员列表失败'
        this.membersData = []
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 获取头像完整URL
     */
    getAvatarUrl(avatar) {
      if (!avatar) {
        return 'https://via.placeholder.com/300x450/cccccc/ffffff?text=No+Photo'
      }
      if (avatar.startsWith('http')) {
        return avatar
      }
      const url = avatar.startsWith('/') ? avatar : `/${avatar}`
      return `${API_BASE_URL}${url}`
    },
    
    /**
     * 清理profile HTML内容，移除不需要的标签
     */
    cleanProfile(profile) {
      if (!profile) return ''
      // 移除Froala Editor的版权信息
      let cleaned = profile.replace(/<p data-f-id="pbf"[^>]*>.*?<\/p>/gi, '')
      // 移除DOCTYPE和html标签
      cleaned = cleaned.replace(/<!DOCTYPE[^>]*>/gi, '')
      cleaned = cleaned.replace(/<html[^>]*>/gi, '')
      cleaned = cleaned.replace(/<\/html>/gi, '')
      cleaned = cleaned.replace(/<head[^>]*>.*?<\/head>/gi, '')
      cleaned = cleaned.replace(/<body[^>]*>/gi, '')
      cleaned = cleaned.replace(/<\/body>/gi, '')
      return cleaned.trim()
    },
    
    /**
     * 清理HTML内容，提取纯文本或保留基本格式
     */
    cleanHtml(html) {
      if (!html) return ''
      // 如果是HTML格式，提取文本内容
      const div = document.createElement('div')
      div.innerHTML = html
      return div.textContent || div.innerText || ''
    },
    
    /**
     * 根据 sequence_id 返回对应的网格样式类
     */
    getGridClass(sequenceId) {
      // Research Assistant Professor (2) 和 Postdoctoral Fellow (3) 使用 2 列布局
      if (sequenceId === 2 || sequenceId === 3) {
        return 'assistants-grid'
      }
      // Research & Administrational Assistants (17) 使用 2 列布局
      if (sequenceId === 17) {
        return 'assistants-grid'
      }
      // PhD Students (18) 和其他使用 3 列布局
      return 'phd-grid'
    }
  }
}
</script>

<style scoped>
/* Override container width for this page only */
.members-page .container {
  max-width: 1200px;
}

.members-page .page-title {
  text-align: center;
}

/* Override section spacing */
.section {
  margin-bottom: 15px;
  padding: 15px 0;
}

.pi-profile {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 40px;
  margin-top: 30px;
  padding: 35px;
  background-color: #fafafa;
  border-radius: 0;
  border: 1px solid var(--border-color);
}

.pi-image {
  width: 300px;
  border-radius: 8px;
  overflow: hidden;
  display: block;
  line-height: 0;
  background: transparent;
}

.pi-image img {
  width: 100%;
  height: auto;
  display: block;
  border-radius: 8px;
}

.pi-info h3 {
  color: #333;
  font-size: 1.8em;
  margin-bottom: 10px;
  font-weight: normal;
}

.title {
  color: var(--primary-color);
  font-size: 1.05em;
  font-weight: normal;
  margin-bottom: 20px;
}

.bio {
  color: var(--text-color);
  line-height: 1.8;
  margin-bottom: 20px;
}

.bio :deep(p) {
  margin-bottom: 15px;
}

.bio :deep(p:last-child) {
  margin-bottom: 0;
}

.research-interests {
  margin-top: 15px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  color: var(--text-color);
  line-height: 1.6;
}

.research-interests strong {
  color: var(--secondary-color);
}

.contact-info {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.contact-info p {
  margin: 10px 0;
  color: var(--text-color);
}

.links {
  display: flex;
  gap: 15px;
}

/* Assistants Grid - 2 per row */
.assistants-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30px;
  margin-top: 30px;
}

/* PhD and Master Grid - 3 per row */
.phd-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  margin-top: 30px;
}

.member-card {
  background-color: white;
  border: 1px solid var(--border-color);
  border-radius: 0;
  padding: 12px;
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.member-image {
  flex-shrink: 0;
  width: 120px;
  overflow: hidden;
  background-color: #f0f0f0;
  border-radius: 8px;
  display: inline-block;
  line-height: 0;
}

.member-image img {
  width: 100%;
  height: auto;
  display: block;
  border-radius: 8px;
  transition: transform 0.3s ease;
}

.member-image:hover img {
  transform: scale(1.05);
}

.member-info {
  flex: 1;
  min-width: 0;
  text-align: left;
}

.member-info h3 {
  color: var(--secondary-color);
  margin: 0 0 6px 0;
  font-size: 1.15em;
  font-weight: 600;
}

.member-subtitle {
  color: var(--primary-color);
  font-size: 0.85em;
  margin: 0 0 8px 0;
}

.member-detail {
  color: var(--text-color);
  font-size: 0.85em;
  line-height: 1.6;
  margin: 6px 0;
}

.member-detail strong {
  color: var(--secondary-color);
  font-weight: 600;
}

.member-detail a {
  color: var(--primary-color);
  text-decoration: none;
}

.member-detail a:hover {
  text-decoration: underline;
}

.loading {
  text-align: center;
  padding: 60px 0;
  color: #666;
  font-size: 1.1em;
}

.error {
  text-align: center;
  padding: 60px 0;
  color: #e74c3c;
  font-size: 1.1em;
}

/* Alumni Grid - 2 per row */
.alumni-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30px;
  margin-top: 30px;
}

.alumni-card {
  background-color: white;
  border: 1px solid var(--border-color);
  border-radius: 0;
  padding: 25px;
  transition: box-shadow 0.3s ease;
}

.alumni-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.alumni-card h3 {
  color: var(--secondary-color);
  margin: 0 0 8px 0;
  font-size: 1.3em;
  font-weight: 600;
}

.alumni-subtitle {
  color: var(--primary-color);
  font-size: 0.95em;
  margin: 0 0 12px 0;
}

.alumni-detail {
  color: var(--text-color);
  font-size: 0.9em;
  line-height: 1.7;
  margin: 8px 0;
}

.alumni-detail strong {
  color: var(--secondary-color);
  font-weight: 600;
}

/* Post Members Grid */
.post-members-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-top: 30px;
}

.post-member-card {
  background-color: white;
  border: 1px solid var(--border-color);
  border-radius: 0;
  padding: 20px;
  transition: box-shadow 0.3s ease;
}

.post-member-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.post-member-card h3 {
  color: var(--secondary-color);
  margin: 0 0 12px 0;
  font-size: 1.2em;
  font-weight: 600;
}

.post-member-detail {
  color: var(--text-color);
  font-size: 0.9em;
  line-height: 1.6;
  margin: 8px 0;
}

.post-member-detail strong {
  color: var(--secondary-color);
  font-weight: 600;
}

@media (max-width: 1024px) {
  .phd-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .pi-profile {
    grid-template-columns: 1fr;
    text-align: center;
  }
  
  .pi-image {
    max-width: 300px;
    margin: 0 auto;
  }
  
  .links {
    justify-content: center;
  }
  
  .assistants-grid,
  .phd-grid,
  .alumni-grid,
  .post-members-grid {
    grid-template-columns: 1fr;
  }
}
</style>

